﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace SX.Utils
{
    public  static  class HostHelper
    {
        #region 定值
        private const string WebConfigPath = "~/web.config";
        private const string RefreshHtmlPath = "~/refresh.html";
        private const string HostRestartPath = "~/bin/HostRestart";
        #endregion

        /// <summary>
        /// 应用程序路径
        /// </summary>
        public static string AppPath
        {
            get { return HostingEnvironment.ApplicationVirtualPath; }
        }

        /// <summary>
        /// 是否根
        /// </summary>
        public static bool IsBaseApp
        {
            get { return HostingEnvironment.ApplicationVirtualPath == "/"; }
        }

        /// <summary>
        /// 通过相对路径获取绝对路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string MapPath(string path) { 
          return HostingEnvironment.MapPath(path);
        }

        private static bool TryWriteWebConfig()
        {
            try
            {
                // In medium trust, "UnloadAppDomain" is not supported. Touch web.config
                // to force an AppDomain restart.
                File.SetLastWriteTimeUtc(HostHelper.MapPath(WebConfigPath), DateTime.UtcNow);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private static bool TryWriteBinFolder()
        {
            try
            {
                var binMarker = HostHelper.MapPath(HostRestartPath);
                Directory.CreateDirectory(binMarker);

                using (var stream = File.CreateText(Path.Combine(binMarker, "marker.txt")))
                {
                    stream.WriteLine("Restart on '{0}'", DateTime.UtcNow);
                    stream.Flush();
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 重启应用程序域
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public static bool RestartAppDomain()
        {
            bool result = TryWriteBinFolder() || TryWriteWebConfig();
            return result;
        } 
    }
}
